import EventEmitter from 'events';
import log4js from 'koa-log4';

import messageHandler from '../handler/messageHandler';
import User from '../models/user';

// robot handlers
import offdutyReply from './offdutyReply';
import queueWatcher from './queueWatcher';
import weChatWait from './weChatWait';

import skynetMessage from './skynetMessage';

// internal handlers
import urgentReplacementRobot from './internalRobots/urgentTeacherReplacementRobot';
import tags from './internalRobots/tags';

const robotLogger = log4js.getLogger('ROBOT');
class RobotMessageDispatcher extends EventEmitter {
  constructor(...args) {
    super(...args);
    this.dispatchEvent = this.dispatchEvent.bind(this);
  }

  async dispatchInternalEvent(tag, event) {
    this.emit('internalMessage', {
      tag,
      event,
      messageHandler,
    });
  }

  async dispatchEvent(messagePayload) {
    const messageFromUserId = messagePayload.fromUser.id;
    const fromUser = await User.findById(messageFromUserId).populate('group');

    if (fromUser.isRobot) return;

    robotLogger.info('Receive Message', messagePayload.fromUser.jiuquId, messagePayload.body);
    this.emit('onMessage', {
      message: messagePayload,
      user: fromUser,
      messageHandler,
    });
  }

  registerRobotHandlers(...handlers) {
    handlers.forEach(handler => this.on('onMessage', handler.handle.bind(handler)));
  }

  registerInternalHandler(...handlers) {
    handlers.forEach(handler => this.on('internalMessage', handler.handle.bind(handler)));
  }
}

const robotMessageDispatcher = new RobotMessageDispatcher();

robotMessageDispatcher.registerRobotHandlers(offdutyReply, skynetMessage, queueWatcher, weChatWait);
robotMessageDispatcher.registerInternalHandler(urgentReplacementRobot);

export default robotMessageDispatcher;
export { tags };
